<?php
/*
Plugin Name: IP2Location Redirect with Confirmation for Chinese Mainland
Description: 一个基于 IP2Location 数据库的插件，用于检测用户是否位于指定地区，并弹出对话框让用户确认是否跳转。
Version: 1.0.0
Author: SK Studio
License: GPL v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/

if (!defined('ABSPATH')) {
    exit; // 防止直接访问
}
const IP2LOCATION_PATH = '/var/www/skstudio-global-wordpress/wp-content/plugins/ip2location-redirection';
const IP2LOCATION_DB_PATH = '/var/www/skstudio-global-wordpress/wp-content/uploads/ip2location/';

// 添加设置菜单
function ip2location_redirect_add_admin_menu() {
    add_options_page(
        '重定向设置',
        'IP2Location重定向',
        'manage_options',
        'ip2location_redirect',
        'ip2location_redirect_options_page'
    );
}
add_action('admin_menu', 'ip2location_redirect_add_admin_menu');

// 注册设置
function ip2location_redirect_settings_init() {
    register_setting('ip2location_redirect', 'ip2location_redirect_settings');

    add_settings_section(
        'ip2location_redirect_section',
        '重定向设置',
        'ip2location_redirect_section_callback',
        'ip2location_redirect'
    );

    add_settings_field(
        'target_country',
        '目标国家代码',
        'ip2location_redirect_country_render',
        'ip2location_redirect',
        'ip2location_redirect_section'
    );

    add_settings_field(
        'redirect_url',
        '重定向URL',
        'ip2location_redirect_url_render',
        'ip2location_redirect',
        'ip2location_redirect_section'
    );

    add_settings_field(
        'confirmation_message',
        '确认提示信息',
        'ip2location_redirect_message_render',
        'ip2location_redirect',
        'ip2location_redirect_section'
    );
}
add_action('admin_init', 'ip2location_redirect_settings_init');

// 修改国家选择字段的渲染函数
function ip2location_redirect_country_render() {
    $options = get_option('ip2location_redirect_settings');
    $selected_country = isset($options['target_country']) ? $options['target_country'] : 'CN';
    $countries = ip2location_redirect_get_countries();
    
    ?>
    <select name='ip2location_redirect_settings[target_country]' class="ip2location-country-select">
        <?php foreach ($countries as $code => $name): ?>
            <option value="<?php echo esc_attr($code); ?>" 
                <?php selected($selected_country, $code); ?>>
                <?php echo esc_html($code . ' - ' . $name); ?>
            </option>
        <?php endforeach; ?>
    </select>
    <p class="description">选择需要重定向的目标国家/地区</p>
    <?php
}

function ip2location_redirect_url_render() {
    $options = get_option('ip2location_redirect_settings');
    ?>
    <input type='url' name='ip2location_redirect_settings[redirect_url]' 
           value='<?php echo isset($options['redirect_url']) ? esc_url($options['redirect_url']) : 'https://www.skstudio.cn'; ?>'>
    <?php
}

function ip2location_redirect_message_render() {
    $options = get_option('ip2location_redirect_settings');
    ?>
    <textarea name='ip2location_redirect_settings[confirmation_message]' rows='3' cols='50'><?php 
        echo isset($options['confirmation_message']) ? esc_textarea($options['confirmation_message']) : '检测到您位于目标地区，是否跳转到对应的网站？';
    ?></textarea>
    <?php
}

// 设置页面回调
function ip2location_redirect_section_callback() {
    echo '配置IP2Location重定向的相关设置';
}

// 添加管理界面样式
function ip2location_redirect_admin_styles($hook) {
    // 只在插件设置页面加载样式
    if ('settings_page_ip2location_redirect' !== $hook) {
        return;
    }
    wp_enqueue_style(
        'ip2location-redirect-admin',
        plugins_url('assets/css/admin.css', __FILE__),
        array(),
        '1.0.0'
    );
}
add_action('admin_enqueue_scripts', 'ip2location_redirect_admin_styles');

// 添加管理界面脚本和样式
function ip2location_redirect_admin_scripts($hook) {
    if ('settings_page_ip2location_redirect' !== $hook) {
        return;
    }
    
    // 加载Select2
    wp_enqueue_style('select2', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css', array(), '4.1.0');
    wp_enqueue_script('select2', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js', array('jquery'), '4.1.0', true);
    
    // 加载自定义样式
    wp_enqueue_style('ip2location-redirect-admin', plugins_url('assets/css/admin.css', __FILE__), array(), '1.0.0');
    
    // 初始化Select2
    wp_add_inline_script('select2', '
        jQuery(document).ready(function($) {
            $(".ip2location-country-select").select2({
                placeholder: "选择国家/地区",
                allowClear: true,
                width: "300px"
            });
        });
    ');
}
add_action('admin_enqueue_scripts', 'ip2location_redirect_admin_scripts');

// 设置页面HTML
function ip2location_redirect_options_page() {
    ?>
    <div class="wrap">
        <form action='options.php' method='post' class="ip2location-redirect-settings">
            <h2>IP2Location重定向设置</h2>
            <?php
            settings_fields('ip2location_redirect');
            do_settings_sections('ip2location_redirect');
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

// 主逻辑：检测 IP 并在页面加载后注入 JavaScript
function ip2location_redirect_check() {
    // 引入 IP2Location PHP 库
    if (file_exists(IP2LOCATION_PATH.'ip2location.php')) {
        require_once IP2LOCATION_PATH.'ip2location.php';
    } else {
        error_log('IP2Location library file missing: '.IP2LOCATION_PATH.'ip2location.php');
        return; // 停止插件执行，避免致命错误
    }

    // 定义 IP2Location 数据库的绝对路径
    $database_path = IP2LOCATION_DB_PATH.'IP2LOCATION-LITE-DB1.BIN';

    // 检查数据库文件是否存在
    if (!file_exists($database_path)) {
        error_log('IP2Location 数据库文件未找到：' . $database_path);
        return; // 数据库不存在时直接返回
    }

    // 初始化 IP2Location 数据库
    $ip2location = new \IP2Location\Database($database_path, \IP2Location\Database::FILE_IO);

    // 获取用户的 IP 地址
    $ip_address = $_SERVER['REMOTE_ADDR'];

    // 获取设置
    $options = get_option('ip2location_redirect_settings', [
        'target_country' => 'CN',
        'redirect_url' => 'https://www.skstudio.cn',
        'confirmation_message' => '检测到您位于目标地区，是否跳转到对应的网站？'
    ]);

    // 查询用户IP的国家信息
    $record = $ip2location->lookup($ip_address, \IP2Location\Database::ALL);

    // 检查用户是否位于目标国家
    if (isset($record['countryCode']) && $record['countryCode'] === $options['target_country']) {
        add_action('wp_footer', function () use ($options) {
            ?>
            <script type="text/javascript">
                document.addEventListener("DOMContentLoaded", function () {
                    var userConfirm = confirm("<?php echo esc_js($options['confirmation_message']); ?>");
                    if (userConfirm) {
                        window.location.href = "<?php echo esc_js($options['redirect_url']); ?>";
                    }
                });
            </script>
            <?php
        });
    }
}

// 将检测逻辑挂载到 init 钩子
add_action('init', 'ip2location_redirect_check');

// 后台提示：如果数据库文件缺失，显示警告
function ip2location_redirect_admin_notice() {
    $database_path = IP2LOCATION_DB_PATH.'IP2LOCATION-LITE-DB1.BIN';
    if (!file_exists($database_path)) {
        echo '<div class="notice notice-error"><p>IP2Location 数据库文件未找到，请确保 <strong>' . esc_html($database_path) . '</strong> 存在。</p></div>';
    }
}
add_action('admin_notices', 'ip2location_redirect_admin_notice');

// 插件停用时清理
function ip2location_redirect_deactivate() {
    // 插件停用时可在此添加清理逻辑
}
register_deactivation_hook(__FILE__, 'ip2location_redirect_deactivate');

// 获取所有国家列表
function ip2location_redirect_get_countries() {
    if (file_exists(IP2LOCATION_PATH.'ip2location.php')) {
        require_once IP2LOCATION_PATH.'ip2location.php';
    } else {
        return array('CN' => '中国'); // 如果库不存在，返回默认值
    }

    $database_path = IP2LOCATION_DB_PATH.'IP2LOCATION-LITE-DB1.BIN';
    if (!file_exists($database_path)) {
        return array('CN' => '中国');
    }

    try {
        $ip2location = new \IP2Location\Database($database_path, \IP2Location\Database::FILE_IO);
        return $ip2location->getCountryNames(); // 获取所有国家列表
    } catch (Exception $e) {
        error_log('IP2Location获取国家列表失败：' . $e->getMessage());
        return array('CN' => '中国');
    }
}
